package frog.lazy.framework.core.tools;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import lombok.SneakyThrows;

import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class FileUtils extends FileUtil {

    @SneakyThrows
    public static void main(String[] args) {
//        InputStream is = URLUtil.getStream(new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1591274158480&di=0536b2f5b906efd718256e5c9f209979&imgtype=0&src=http%3A%2F%2Fimg9.itboth.com%2F28%2F07%2Frm2ERb.jpg"));
//        File file = File.createTempFile(IdUtils.fastSimpleUUID(), ".png");
//        FileUtil.writeFromStream(is, file);
//        Map<String, Object> resultMap =  new HashMap();
//        ImgUtils.createImage(file, resultMap);
        System.out.println(suffix("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1591274158480&di=0536b2f5b906efd718256e5c9f209979&imgtype=0&src=http%3A%2F%2Fimg9.itboth.com%2F28%2F07%2Frm2ERb.jpg"));

    }

    @SneakyThrows
    public static File urlToFile(String url) throws MalformedURLException {
        try(InputStream is = URLUtil.getStream(new URL(url))){
            File file = File.createTempFile(IdUtils.fastSimpleUUID(), suffix(url));
            FileUtil.writeFromStream(is, file);
            return file;
        }
    }

    public static String suffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }
}
